package com.mandao.oneplat.boot;

import com.mandao.oneplat.boot.dao.OneMongoDao;
import com.mandao.oneplat.boot.handler.OneServerControlHandler;
import com.mandao.oneplat.boot.handler.OneServerPostHandler;
import com.mandao.oneplat.boot.handler.OneServerPreHandler;
import com.mandao.oneplat.boot.handler.OneServerViewHandler;
import com.mandao.oneplat.boot.ioc.OneIocFactory;
import com.mandao.oneplat.boot.mvc.control.OneControllerDispacher;
import com.mandao.oneplat.boot.mvc.view.OneViewResolver;
import com.mandao.oneplat.boot.support.cache.CacheAssetsImpl;
import com.mandao.oneplat.boot.support.cache.ICacheAssets;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * Created by sunson on 2017/3/21.
 */
public class OnePlatBootChannel extends ChannelInitializer<SocketChannel> {

   private OnePlatConfig oneOption;
   private OneControllerDispacher oneControllerDispacher;
   private OneViewResolver oneViewResolver;
   private ICacheAssets cacheAssets;
   private OneMongoDao oneMongoDao;

    public OnePlatBootChannel(OnePlatConfig oneOption) throws Throwable {
        this.oneOption = oneOption;
        oneMongoDao = new OneMongoDao(oneOption);
        OneIocFactory.initIoc(oneOption, oneMongoDao);
        //
        oneControllerDispacher = new OneControllerDispacher(oneOption);
        oneViewResolver = new OneViewResolver(oneOption);
        cacheAssets = new CacheAssetsImpl(oneOption);
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpServerCodec()); // HTTP解码，编码
        p.addLast(new HttpContentCompressor());  // 支持GZIP压缩的请求，返回压缩
        p.addLast(new OneServerPostHandler()); // HTTP返回终处理
        p.addLast(new OneServerViewHandler(oneViewResolver, oneOption)); // 返回视图处理
        p.addLast(new OneServerPreHandler(oneOption, cacheAssets)); // HTTP业务前处理
        p.addLast(new OneServerControlHandler(oneControllerDispacher, oneOption)); // 业务控制器处理
    }
}
